package org.sonar.plugin.deltacoverage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.mapper.MapperWrapper;

/**
 * Class to read existing code coverage report and populates in memory graph of current code coverage.
 * 
 * @author Abhijeet_Kesarkar
 *
 * @see ModuleCoverage
 */
public class CoverageReportReader {

	/**
	 * Reads the specified code coverage report in xml format.
	 * Uses xstream to convert from XML to java object.
	 * Xstream aliases are used to bridge gap between xml format and java object structure.
	 * 
	 * @param coverageReport path to existing xml coverage report file
	 * @return {@link ModuleCoverage} instance
	 */
	public static ModuleCoverage getCoverageData(File coverageReport) throws FileNotFoundException
	{
		XStream xstream = new XStream() {
		    @Override
		    protected MapperWrapper wrapMapper(MapperWrapper next) {
		        return new MapperWrapper(next) {
		            @Override
		            public boolean shouldSerializeMember(Class definedIn, String fieldName) {
		                if (definedIn == Object.class) {
		                    return false;
		                }
		                return super.shouldSerializeMember(definedIn, fieldName);
		            }
		        };
		    }
		};
		xstream.setClassLoader(CoverageReportReader.class.getClassLoader());
		xstream.alias("coverage", ModuleCoverage.class);
		xstream.useAttributeFor(ModuleCoverage.class, "lineRate");
		xstream.useAttributeFor(ModuleCoverage.class, "branchRate");
		xstream.useAttributeFor(ModuleCoverage.class, "hitLines");
		xstream.useAttributeFor(ModuleCoverage.class, "totalLines");
		xstream.useAttributeFor(ModuleCoverage.class, "hitBranches");
		xstream.useAttributeFor(ModuleCoverage.class, "totalBranches");
        
				
        xstream.aliasAttribute("line-rate", "lineRate");
        xstream.aliasAttribute("branch-rate", "branchRate");
        xstream.aliasAttribute("lines-covered", "hitLines");
        xstream.aliasAttribute("branches-covered", "hitBranches");
        xstream.aliasAttribute("lines-valid", "totalLines");
        xstream.aliasAttribute("branches-valid", "totalBranches");
        
		return (ModuleCoverage) xstream.fromXML(new FileInputStream(coverageReport));
	}
}
